# coding:utf-8
from odoo import models, fields, api, _
from odoo.exceptions import Warning
import odoo.addons.decimal_precision as dp


class PaulSaleOrderLineExtend(models.Model):
    _name = 'sale.order.line'
    _inherit = ["sale.order.line", "stock.view.quant.mixin"]

    qty_returned = fields.Float(string="Returned Qty", digits=dp.get_precision('Product Unit of Measure'), compute='_get_qty_returned')
    permissible_proportion = fields.Float(u'允出比例%', related='product_id.product_tmpl_id.permissible_proportion', readonly=True)
    proportion = fields.Float(u'允出数量', compute='_compute_proportion')
    minimum_sales_qty = fields.Float(string=u'最小起订量', copy=False, readonly=True,
                                     digits=dp.get_precision('Product Unit of Measure'),
                                     related='product_id.product_tmpl_id.minimum_sales_qty')
    customer_order = fields.Char('Customer Order')
    technological_requirements = fields.Char('Technological Requirements')
    note = fields.Char('Note')
    lot = fields.Char('Lot')
    length_weight = fields.Char('Length/Weight')
    origin_id = fields.Integer('Origin ID')
    readonly_uom_id = fields.Many2one('product.uom', string=u'计量单位', related='product_id.uom_id',
                                      readonly=True, store=True)
    client_order_ref = fields.Char(related='order_id.client_order_ref', string=u'客户订单号', store=True, readonly=True)
    country_id = fields.Many2one("res.country", string=u'出货国家', related="order_id.partner_shipping_id.country_id", readonly=True)
    begin_order_id = fields.Many2one("sale.order", string=u"同组订单", readonly=True, related="order_id.begin_order_id", store=True)

    @api.onchange('product_uom_qty')
    def _compute_proportion(self):
        for line in self:
            line.proportion = round(line.product_uom_qty * (100 + line.product_id.product_tmpl_id.permissible_proportion) * 0.01, 0)

    @api.multi
    def write(self, vals):
        deposit_product_id = self.env['ir.values'].get_default('sale.config.settings', 'deposit_product_id_setting')
        for line in self:
            if line.product_id.product_tmpl_id.enable_minimum_sales_qty and line.product_uom_qty < line.minimum_sales_qty:
                raise Warning(u'商品' + line.product_id.name + u'销售数量不足最小起订量')
        return super(PaulSaleOrderLineExtend, self).write(vals)

    @api.model
    def create(self, vals):
        product = self.env['product.product'].browse(vals['product_id'])
        if product.product_tmpl_id.enable_minimum_sales_qty and vals['product_uom_qty'] < product.product_tmpl_id.minimum_sales_qty:
            raise Warning(u'商品' + product.name + u'销售数量不足最小起订量')
        vals['proportion'] = round(vals['product_uom_qty'] * (100 + self.env['product.product'].browse(vals['product_id']).product_tmpl_id.permissible_proportion) * 0.01, 0)
        return super(PaulSaleOrderLineExtend, self).create(vals)

    def _get_qty_returned(self):
        for line in self:
            total = 0.0
            for move in line.procurement_ids.mapped('move_ids').filtered(lambda r: r.state == 'done' and not r.scrapped):
                if move.location_dest_id.usage != "customer" and move.origin_returned_move_id:
                    total += move.product_uom._compute_quantity(move.product_uom_qty, line.product_uom)
            line.update({'qty_returned': total})

    @api.multi
    def action_view_quants_by_item(self):
        return self.action_view_quant_by_product_ids([self.product_id.id])

    @api.multi
    @api.onchange('product_id')
    def product_id_change(self):
        res = super(PaulSaleOrderLineExtend, self).product_id_change()
        vals = {}
        vals['product_uom_qty'] = 0.0
        self.update(vals)
        return res

    # 暂时关闭‘库存不足’的提示 req302
    @api.onchange('product_uom_qty', 'product_uom', 'route_id')
    def _onchange_product_id_check_availability(self):
        res = super(PaulSaleOrderLineExtend, self)._onchange_product_id_check_availability()
        return {}